package com.tonghai.controller;

import com.tonghai.domain.Girl;
import com.tonghai.repository.GirlRepository;
import com.tonghai.repository.LessonRepository;
import com.tonghai.service.GirlService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.io.PrintWriter;
import java.util.List;
import java.util.Optional;

@CrossOrigin
@RestController
public class GirlController {

    @Autowired
    private GirlRepository girlRepository;

    @Autowired
    private LessonRepository lessonRepository;

    @Autowired
    public GirlService girlService;

    //开始遍历所有数据
    @RequestMapping("/jsonGirls")
    public List<Girl> jsonGirls(){
        List<Girl> girlList = girlRepository.findAll();
        return girlList;
    }

    /**
     * 添加一个女生
     * @return
     */
    @RequestMapping(value = "/insertGirl")
    public Girl addGirl(@Valid Girl girl, BindingResult bindingResult){
        if(bindingResult.hasErrors()){
            System.out.println(bindingResult.getFieldError().getDefaultMessage());
            return null;
        }
        Girl girl1 = girlRepository.save(girl);
        return girl1;
    }

    //通过id查询
    @RequestMapping(value = "/selectOne")
    public List<Girl> girlFindOne(@RequestParam("id") Integer id){
        if (id == null){
            return girlRepository.findAll();
        }
        return girlRepository.findAllById(id);
    }

    //更新
    @RequestMapping(value = "/update")
    public Girl girlUpdate(@Valid Girl girl, BindingResult bindingResult){
        if(bindingResult.hasErrors()){
            System.out.println(bindingResult.getFieldError().getDefaultMessage());
            return null;
        }
        Girl girl1 = girlRepository.save(girl);
        return girl1;
    }

    //删除
    @RequestMapping(value = "/delete")
    public int girlDelete(@RequestParam("id") Integer id){
        int num=1;
        girlRepository.deleteById(id);
        return num;
    }


    /*@RequestMapping(value = "/selectMore")
    public String selectMoreLesson(@RequestParam("id") Integer id,Model model){
        System.out.println("数据源："+lessonRepository.findAllById(id));
        model.addAttribute("lesList",lessonRepository.findAllById(id));
        return "selectMore";
    }*/
}
